module ApplicationHelper
  def full_title(page_title)
    base_title = I18n.t('navigation.web_name')
    if page_title.empty?
      base_title
    else
      "#{base_title} | #{page_title}"
    end
  end

  def active_page(path)
    current_page?(path) ? "active" : "none"
  end

  def active_controller(name)
    controller_path == name ? "active" : "none"
  end

  def namespace_name
    controller_path.split('/').first
  end

  def active_namespace(name)
    namespace_name == name ? "active" : "none"
  end

  def has_add?(id, controller_name, suffix)
    case "#{suffix}_#{controller_name}"
      when "left_programs"
        LeftProgram.exists?(id)
      when "right_programs"
        RightProgram.exists?(id)
      when "left_series"
        LeftSeries.exists?(id)
      when "right_series"
        RightSeries.exists?(id)
      else
        false
    end
  end

  def append_url(url, params)
    concat = URI::parse(url).query ? "&" : "?"
    "#{url}#{concat}#{params.to_query}"
  end

  def protect_params(params)
    params[:controller_name] = params[:controller]
    params[:action_name] = params[:action]
    params.delete(:controller)
    params.delete(:action)
    params
  end
end

class ActiveRecord::Base
  def self.truncate
    connection.execute("TRUNCATE #{self.table_name}")
  end

  def self.search(params)
    if params[:name]
      where('Name LIKE ?', "%#{params[:name]}%")
    else
      where(1)
    end
  end

  def self.import(file)
    spreadsheet = open_spreadsheet(file)
    ids = []
    (2..spreadsheet.last_row).each { |i| ids << spreadsheet.row(i)[0] }
    where(:MediaCode => ids)
  end

  def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
      when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
      when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)
      else raise "Unknown file type: #{file.original_filename}"
    end
  end

  def self.sort(str)
    sorter = ""
    unless str.nil?
      arr = []
      YAML.load(str).each do |s|
        arr.append("#{s['property']} #{s['direction']}")
      end
      sorter = arr.join(',')
    end
    order(sorter)
  end

  def self.filt(str)
    filter = 1
    unless str.nil?
      arr = []
      YAML.load(str).each do |s|
        case s['operator']
          when 'like'     then arr.append("#{s['property']} LIKE '%#{s['value']}%'")
          when 'lt'       then arr.append("#{s['property']} <= #{s['value']}")
          when 'gt'       then arr.append("#{s['property']} >= #{s['value']}")
          when 'eq', '='  then arr.append("#{s['property']} = #{s['value']}")
          when 'in'       then arr.append("#{s['property']} IN (#{s['value'].join(',')})")
        end
      end
      filter = arr.join(' AND ')
    end
    where(filter)
  end
end
